package com.sample.kokou;

import android.widget.TextView;
import java.sql.SQLException;

import android.view.View;

import android.os.Bundle;

import com.j256.ormlite.android.apptools.OrmLiteBaseActivityGroup;
import com.j256.ormlite.dao.Dao;

public class PersonActivity extends OrmLiteBaseActivityGroup<SampleDBHelper> {
	private Dao<Person, Integer> dao = null;

	private TextView nameView = null;
	private TextView ageView = null;
	
	private Bundle extraMap = null;
	private Person person = new Person();
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO 自動生成されたメソッド・スタブ
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_person);
        
        try { 
        	dao = getHelper().getDao(Person.class);
        } catch (SQLException e) { 
        	throw new RuntimeException(e); 
        }
        nameView = GenericUtil.getView(this, R.id.nameText);
        ageView = GenericUtil.getView(this, R.id.ageText);
        
        extraMap = getIntent().getExtras();
        if ( extraMap.getString("action").equals("edit") ) {
        	int id = (int)extraMap.getLong("id");
            try {
            	person = dao.queryForId(id);
            	nameView.setText(person.getName());
            	ageView.setText(String.format("%d",person.getAge()));
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
            
        }
    }

    public void onCancel(View v) {
        finish();
    }

    public void onOk(View v) {
    	person.setName(nameView.getText().toString());
        person.setAge(Integer.parseInt(ageView.getText().toString()));
        
        try {
        	if ( extraMap.getString("action").equals("new") ) {
        		dao.create(person);
        	} else {
        		dao.update(person);
        	}
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finish();
    }
    
}
